import indexConfig from '@/common/config/index-config.js'
import socketMessageTypeEnum from '@/common/enum/socket-message-type.enum.js'
import $helpers from '@/common/utils/helpers.js';
import $bluetooth from '@/common/utils/linkBluetooth.js'
import $storageKeyEnum from '@/common/enum/storage-key.enum.js'
import { eventBus } from '@/main.js'
class websocketUtil {
	constructor() {
		this.is_open_socket = false //避免重复连接
		this.data = {
			type: "CLIENT_HEARTBEAT",
			memberId: '',
			username:'',
		}
		this.heartbeatInterval = null //检测服务器端是否还活着
		this.reconnectTimeOut = null //重连之后多久再次重连
		this.username = null;
		this.socketTask = null;

		try {
			return this.userInformationVerification()
		} catch (e) {
			console.log('catch');
			this.is_open_socket = false
			this.reconnect();
		}
	}
	//获取用户信息
	userInformationVerification() {
		const MAX_ATTEMPTS = 10;
		const RETRY_INTERVAL = 500;
		let attempt = 0;

		const intervalId = setInterval(() => {
			let memberInfo = $helpers.getCache($storageKeyEnum.member_info);

			if (uni.$u.test.isEmpty(memberInfo)) {
				console.log(`尝试重新获取用户信息 ${attempt + 1}/${MAX_ATTEMPTS}`);
				attempt++;

				if (attempt >= MAX_ATTEMPTS) {
					clearInterval(intervalId);
					console.error('达到最大重试次数，未获取到用户信息');
				}
			} else {
				clearInterval(intervalId);
				this.connectSocketInit(memberInfo);
			}
		}, RETRY_INTERVAL);
	}
	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit(memberInfo) {
		this.socketTask = uni.connectSocket({
			url: indexConfig.webSocketURL,
			success: (res) => {
				console.log("正准备建立websocket中...",res);
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			this.username = "client_"+memberInfo.id;
			let data = {
				type: "CLIENT_BIND",
				username: this.username,
			}

			this.send(data)
			console.log("WebSocket连接正常！");
			clearTimeout(this.reconnectTimeOut)
			clearTimeout(this.heartbeatInterval)
			this.is_open_socket = true;
			this.start();
			eventBus.$emit('webSocketReconnect', 1)
			// 注：只有连接正常打开中 ，才能正常收到消息
			this.socketTask.onMessage((res) => {
				console.log('消息内容', res.data)
				const msg = JSON.parse(res.data);
				if (msg.type == socketMessageTypeEnum.CLIENT_HEARTBEAT){
					getApp().globalData.socketId = msg.id;
				}else if(msg.type == socketMessageTypeEnum.CLIENT_MESSAGE){
					if(!uni.$u.test.isEmpty(msg.command)){
						$bluetooth.sendMy(msg.command,0);
					}
				}
			});
		})
		// 监听连接失败，这里代码我注释掉的原因是因为如果服务器关闭后，和下面的onclose方法一起发起重连操作，这样会导致重复连接
		// uni.onSocketError((res) => {
		// 	console.log('WebSocket连接打开失败，请检查！');
		// 	this.is_open_socket = false;
		// 	this.reconnect();
		// });
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			console.log("已经被关闭了")
			this.is_open_socket = false;
			this.reconnect();
		})
	}

	//发送消息
	send(value) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		this.socketTask.send({
			data: JSON.stringify(value),
			async success() {
				// console.log("消息发送成功");
			},
		});
	}
	//开启心跳检测
	start() {
		this.data.username = this.username;
		this.send(this.data)
		this.heartbeatInterval = setInterval(() => {
			// console.log(this.data)
			this.send(this.data);
		}, 30000)
	}
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!this.is_open_socket) {
			this.reconnectTimeOut = setTimeout(() => {
				this.userInformationVerification();
			}, 3000)
		}
	}
	//外部获取消息
	getMessage(callback) {
		this.socketTask.onMessage((res) => {
			return callback(res)
		})
	}

	// // 发送消息
	// let data={value:"传输内容",method:"方法名称"}
	// this.$socket.send(JSON.stringify(data));

	// // 接收消息
	// this.$socket.getMessage(res=>{
	// 	console.log(res);
	// })
}

module.exports = websocketUtil
